'use strict';
module.exports = {
	/**
	 * 通过主键删除类型
	 * @url client/typeData/kh/delTypeDataById 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _, $ } = util;
		let { uid, typeData } = data;
		let res = { code: 0, msg: "删除成功" };
		// 业务逻辑开始-----------------------------------------------------------
		if(typeData == null ){
			return { code : 1001, msg : '参数错误' };
		}
		
		let { _id,icon,name } = typeData;
		if(pubFun.isEmpty(_id) || pubFun.isEmpty(icon) || pubFun.isEmpty(name)){
			return { code : 1001, msg : '参数错误' };
		}
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 删除类型
			const row = await vk.daoCenter.typeDateDao.deleteById(typeData._id, transaction);
			if (row == null || row <= 0) {
				throw new Error("删除失败");
			}
			
			// 修改所有数据类型
			await vk.daoCenter.bookKeepingDataDao.update({
				whereJson: {
					uid: _.eq(uid),
					icon: _.eq(icon),
					iconName: _.eq(name)
				},
				dataJson: {
					icon: "其他",
					iconName: "icon-qita"
				}
			});
			
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}